from sqlalchemy.orm import Session
import json
from typing import List
from . import models, schemas


def create_meeting(
    db: Session,
    title: str,
    meeting_time: str = None,
    location: str = None,
    participants: str = None,
    minutes: str = None,
    todos: str = None,
    content: str = None,
    created_by: int = None,
    attachments: List[dict] = None,
):
    """Create a Meeting record and return it.

    This composes a JSON `content` from provided fields (or uses provided
    content if it's a JSON string), writes both the JSON content and
    individual columns (meeting_time, location, ...) for easier querying.
    """
    content_data = {}
    if content:
        try:
            content_data = json.loads(content)
        except Exception:
            content_data = {"raw": content}

    # merge provided fields (form / api) into content_data if present
    if meeting_time:
        content_data.setdefault("meeting_time", meeting_time)
        content_data.setdefault("会议时间", meeting_time)
    if location:
        content_data.setdefault("location", location)
        content_data.setdefault("会议地点", location)
    if participants:
        content_data.setdefault("participants", participants)
        content_data.setdefault("参会人员", participants)
    if minutes:
        content_data.setdefault("minutes", minutes)
        content_data.setdefault("会议纪要", minutes)
    if todos:
        content_data.setdefault("todos", todos)
        content_data.setdefault("待办事项", todos)

    final_content = json.dumps(content_data, ensure_ascii=False)

    # attachments is expected to be a list of dicts: {saved_name, orig_name, remark}
    db_meeting = models.Meeting(
        title=title,
        content=final_content,
        meeting_time=meeting_time or content_data.get("meeting_time") or content_data.get("会议时间"),
        location=location or content_data.get("location") or content_data.get("会议地点"),
        participants=participants or content_data.get("participants") or content_data.get("参会人员"),
        minutes=minutes or content_data.get("minutes") or content_data.get("会议纪要"),
        todos=todos or content_data.get("todos") or content_data.get("待办事项"),
        attachments=json.dumps(attachments, ensure_ascii=False) if attachments else None,
        created_by=created_by,
    )
    db.add(db_meeting)
    db.commit()
    db.refresh(db_meeting)
    return db_meeting


def create_meeting_from_schema(db: Session, meeting: schemas.MeetingCreate, created_by: int):
    """Create meeting from a Pydantic schema object (used by API endpoint)."""
    return create_meeting(
        db=db,
        title=meeting.title,
        meeting_time=getattr(meeting, 'meeting_time', None),
        location=getattr(meeting, 'location', None),
        participants=getattr(meeting, 'participants', None),
        minutes=getattr(meeting, 'minutes', None),
        todos=getattr(meeting, 'todos', None),
        content=getattr(meeting, 'content', None),
        created_by=created_by,
    )


def get_meeting(db: Session, meeting_id: int):
    return db.query(models.Meeting).filter(models.Meeting.id == meeting_id).first()


def delete_meeting(db: Session, meeting: models.Meeting):
    db.delete(meeting)
    db.commit()


def create_resource(
    db: Session,
    core_point: str, 
    source: str = None,
    material_type: str = None, 
    category: str = None,
    note: str = None, 
    created_by: int = None,
   
):
    db_res = models.Resource(
        core_point=core_point,
        source=source,
        material_type=material_type,
        category=category,
        note=note,
        created_by=created_by,
    )
    db.add(db_res)
    db.commit()
    db.refresh(db_res)
    return db_res


def get_resources(db: Session):
    return db.query(models.Resource).order_by(models.Resource.created_at.desc()).all()


def get_resource(db: Session, resource_id: int):
    return db.query(models.Resource).filter(models.Resource.id == resource_id).first()


def update_resource(db: Session, resource: models.Resource, core_point: str = None, source: str = None, material_type: str = None, category: str = None, note: str = None):
    if core_point is not None:
        resource.core_point = core_point
    if source is not None:
        resource.source = source
    if material_type is not None:
        resource.material_type = material_type
    if category is not None:
        resource.category = category
    if note is not None:
        resource.note = note
    db.add(resource)
    db.commit()
    db.refresh(resource)
    return resource
    db.add(resource)
    db.commit()
    db.refresh(resource)
    return resource


def delete_resource(db: Session, resource: models.Resource):
    db.delete(resource)
    db.commit()
